﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

using Wedo.Recognition.Domain;
using Wedo.Recognition.Domain.Models;
using Wedo.Utility;
using Wedo.Domain.Models;
using Wedo.Mvc.Utility;
using System.Data;
using System.Web.Mvc; 
using Wedo.Recognition.Service.Service; 
using Wedo.Recognition.Repository;
using Wedo.Utility.Common;

namespace Wedo.Service.Common
{
    /// <summary>
    /// 用户服务类
    /// </summary>
    public partial class UserService : BaseService<UserInfo> 
    {

        public UserService(IUnitWork dbContext)
            : base(dbContext,dbContext.User)
        { 
        }

        #region 私有方法
         /// <summary>
        /// 在用户信息保存前检查合法性
        /// </summary>
        /// <param name="item"></param>
        private void CheckModelBeforeSave(UserInfo item, List<string> roles, bool isNew)
        {
            item.CheckNull("用户对象不能为空");

            if (roles == null || roles.Count <= 0)
                throw new ArgumentException("用户至少应该含有一个角色");

            var count = _repository.Filter(s => s.Name == item.Name).Count();

            //新增的用户不能重名，更新的用户名可以和自己相同，但不能与已存在的其他用户相同
            if ((isNew && count > 0) || (!isNew && count > 1))
                throw new Exception(string.Format("用户名{0}已存在", item.Name));
        }

        /// <summary>
        /// 转换类型
        /// </summary>
        /// <param name="roles"></param>
        /// <returns></returns>
        private List<Role> GetRolesFormId(List<string> roles)
        {
           return _dbContext.Set<Role>()
               .Filter(m => roles.Any(s => s == m.Id)).ToList(); 
        }


        #endregion

        #region 常用方法


        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="item"></param>
        public void AddUser(UserInfo item, List<string> roles)
        {
            //CheckModelBeforeSave(item, roles, true);
            var ritems = GetRolesFormId(roles);
            item.Id = Guid.NewGuid();
            item.Password = StringHelper.HashPassword(item.Password);
            item.Roles.Clear();
            item.Roles.AddRange(ritems);
             _repository.Create(item);
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="item"></param>
        public void UpdateUser(UserInfo item, List<string> roles)
        {
            //CheckModelBeforeSave(item, roles, false);
            var model = GetById(item.Id);
            if (item.Password.IsNotNullOrWhiteSpace() && item.Password != model.Password)
            {
                item.Password = StringHelper.HashPassword(item.Password);
            }
            _repository.UpdateProperties(model, item);
            var role = GetRolesFormId(roles);
            model.Roles.Clear();
            model.Roles.AddRange(role);
            Commit();
        }

        public IQueryable<UserInfo> GetUserByRole(string role)
        {
            return _repository.Filter(m => m.Roles.Count(s=>s.Id==role)>0);
        }


        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public UserInfo GetUserByName(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName))
                return null;
            var uitem = _repository.Find(s => s.Name.Trim() == userName.Trim());
            return uitem;
        }

        public IEnumerable<IGrouping<Module, Resource>> GetNavigators(string user)
        {

            var u =System.Web.HttpContext.Current.User.Identity as CurrentUser;
            if (u == null)
            {
                return new List<CommonGroup<Module, Resource>>();
            }

            var rep=  _repository as UserRepository;
            var rus = rep.GetRoleResource(u.Roles).Where(m => m.Navigator) ;

            return rus.GroupBy(m => m.Module);
        }

        #endregion

        #region membership

        /// <summary>
        /// 检查用户是否合法，包括是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private UserInfo CheckUserName(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName))
                throw new ArgumentNullException("username", "用户对象不能为空");
            var uitem = GetUserByName( userName);
            if (uitem == null)
                throw new Exception(string.Format("指定的用户名称{0}不存在", userName));
            return uitem;
        }

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Login(string userName, string password)
        {
            string pwd = _dbContext.Set<UserInfo>().Filter(m => m.Name.Trim().ToLower()
                == userName.Trim().ToLower())
                .Select(m => m.Password).FirstOrDefault();
            return StringHelper.HashPassword(password) == pwd;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="oldpass">旧密码</param>
        /// <param name="newPass">新密码</param>
        /// <returns></returns>
        public bool ChangePassword(string userName, string oldpass, string newPass)
        {
            if (string.IsNullOrWhiteSpace(newPass))
                throw new ArgumentNullException("newpass", "新密码不能为空");

            if (oldpass == newPass)
                throw new ArgumentException("新旧密码相同，不需要更改");

            var uitem = CheckUserName(userName);

            if (uitem.Password != StringHelper.HashPassword(oldpass))
                throw new ArgumentException("旧密码不符合", oldpass);

            uitem.Password = StringHelper.HashPassword(newPass);
            uitem.Modified = DateTime.Now;

            Commit();
            return true;
        }

        public CurrentUser GetPageUser(string name)
        {
            var model = GetUserByName(name);
            if (model != null)
            {
                string[] roles = new string[] { };
                if (model.Roles != null && model.Roles.Count >0)
                { 
                    roles = model.Roles.Select(m => m.Id).ToArray();
                }
                return new CurrentUser(model.Name, model.StaffNameEN, roles);

            }
            else
            {
                return null;
            } 
        }
        #endregion
    }
}
